package com.apobates.forum.orize.core.plug;

import com.apobates.forum.orize.core.OrizeSlotResourceMatchStrategy;
import org.apache.commons.lang3.StringUtils;
import java.util.function.Function;
import java.util.stream.Stream;

/**
 * 使用micronaut.io.AntPathMatcher来匹配.
 * 支持: ${占位符}和{占位符}
 * @author xiaofanku@live.cn
 * @since 20210822
 */
public class OrizeSlotResourceAntPathMatchStrategy implements OrizeSlotResourceMatchStrategy {
    private final AntPathMatcher matcher;

    public OrizeSlotResourceAntPathMatchStrategy() {
        this.matcher = new AntPathMatcher();
    }

    @Override
    public boolean match(String requestPath, String resourcePath, String resourceSlotsKey) {
        //将占位符转换成resourcePath中的样式.例: path->{path}
        String[] searchStrArr = Stream.of(resourceSlotsKey.split(",")).map(ele -> {
            return Stream.of("${" + ele + "}", "{" + ele + "}");
        }).flatMap(Function.identity()).toArray(String[]::new);
        String[] replaceStrArr = new String[searchStrArr.length];
        //生成替换后的:*
        replaceStrArr = Stream.of(replaceStrArr).map(ele->"*").toArray(String[]::new);
        //将resourcePath中的占* 例: /board/{path}.xhtml->/board/*.xhtml
        String _pattern = StringUtils.replaceEach(resourcePath, searchStrArr, replaceStrArr);
        return matcher.doMatch(_pattern, requestPath, true);
    }
}
